package com.ruoyi.management.service.impl;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.management.base.config.AmmeterMessageConstants;
import com.ruoyi.management.base.utils.Crc16Utils;
import com.ruoyi.management.base.utils.HexUtils;
import com.ruoyi.management.dao.mapper.AmmeterMapper;
import com.ruoyi.management.dao.mapper.UserMapper;
import com.ruoyi.management.mqtt.MqttProducer;
import com.ruoyi.management.pojo.param.*;
import com.ruoyi.management.pojo.po.QldbqyinfoPO;
import com.ruoyi.management.pojo.po.UserPO;
import com.ruoyi.management.pojo.vo.QLdbzymxVO;
import com.ruoyi.management.pojo.vo.QldbqyinfoVO;
import com.ruoyi.management.pojo.vo.UserResultVO;
import com.ruoyi.management.pojo.vo.ZTVO;
import com.ruoyi.management.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AmmeterMapper ammeterMapper;
    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public boolean add(UserParam userParam) {
        log.debug("新增用户");
        UserPO userPO = new UserPO();
        userPO.setQymc(userParam.getQymc());
        userPO.setKhbh(userParam.getKhbh());
        userPO.setXm(userParam.getXm());
        userPO.setSj(userParam.getSj());
        userPO.setZw(userParam.getZw());
        userPO.setWxh(userParam.getWxh());
        userPO.setQx(userParam.getQx());
        userPO.setTname(userParam.getTname());
        userPO.setTjsj(new Date());
        userPO.setYx(1);
        userPO.setSfjf(userParam.getSfjf());
        userPO.setPassword("123456");
        int a= userMapper.addUser(userPO);
        if(a<0){
            return false;
        }
        return true;
    }

    @Override
    public boolean update(UserParam userParam) {
        log.debug("更新用户");
        UserPO userPO = new UserPO();
        userPO.setYhID(userParam.getYhID());
        userPO.setQymc(userParam.getQymc());
        userPO.setKhbh(userParam.getKhbh());
        userPO.setXm(userParam.getXm());
        userPO.setSj(userParam.getSj());
        userPO.setWxh(userParam.getWxh());
        userPO.setTname(userParam.getTname());
        userPO.setTjsj(new Date());
        userPO.setYx(1);
        userPO.setSfjf(userParam.getSfjf());
        userPO.setZw(userParam.getZw());
        userPO.setQx(userParam.getQx());
        int a= userMapper.update(userPO);
        if(a<0){
            return false;
        }
        return true;
    }

    @Override
    public List<UserResultVO> selectContact(UserParam userParam) {
        log.debug("关联用户的联系人列表");
        return userMapper.selrctContact(userParam);
    }

    @Override
    public List<QLdbzymxVO> selectUseList(AmmeterParam ammeterParam) {
        log.debug("租用中客户信息列表");

        // 当前账号非admin账号
        if (StringUtils.isNotBlank(ammeterParam.getTgszt()) && !"1".equals(ammeterParam.getTgszt())) {
            ZtParam ztParam = new ZtParam();
            ztParam.setTgszt(ammeterParam.getTgszt());
            List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
            if (CollectionUtils.isNotEmpty(ztvos)) {
                ammeterParam.setZt(ztvos.get(0).getNr());
            }
        }
        PageHelper.startPage(ammeterParam.getPageNum(), 10);
        return userMapper.selectUseList(ammeterParam);
    }

    @Override
    public List<QLdbzymxVO> selectFileList(AmmeterParam ammeterParam) {
        log.debug("退租客户信息列表");
        // 当前账号非admin账号
        if (StringUtils.isNotBlank(ammeterParam.getTgszt()) && !"1".equals(ammeterParam.getTgszt())) {
            ZtParam ztParam = new ZtParam();
            ztParam.setTgszt(ammeterParam.getTgszt());
            List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
            if (CollectionUtils.isNotEmpty(ztvos)) {
                ammeterParam.setZt(ztvos.get(0).getNr());
            }
        }
        PageHelper.startPage(ammeterParam.getPageNum(), 10);
        return userMapper.selectFileList(ammeterParam);
    }

    @Override
    public QldbqyinfoVO selectzh(AmmeterParam ammeterParam) {
        return userMapper.selectzh(ammeterParam.getKhbh());
    }

    @Override
    public boolean updateInvoice(QldbqyinfoParam qldbqyinfoParam) {
        log.debug("开票信息补充");
        QldbqyinfoPO qldbqyinfoPO = new QldbqyinfoPO();
        qldbqyinfoPO.setQymc(qldbqyinfoParam.getQymc());
        qldbqyinfoPO.setKhbh(qldbqyinfoParam.getKhbh());
        qldbqyinfoPO.setYyzzh(qldbqyinfoParam.getYyzzh());
        qldbqyinfoPO.setZt(qldbqyinfoParam.getZt());
        qldbqyinfoPO.setJflx(qldbqyinfoParam.getJflx());
        qldbqyinfoPO.setHkzje(qldbqyinfoParam.getHkzje());
        qldbqyinfoPO.setYszje(qldbqyinfoParam.getYszje());
        qldbqyinfoPO.setWszje(qldbqyinfoParam.getWszje());
        qldbqyinfoPO.setKpqymc(qldbqyinfoParam.getKpqymc());
        qldbqyinfoPO.setKpsh(qldbqyinfoParam.getKpsh());
        qldbqyinfoPO.setKplx(qldbqyinfoParam.getKplx());
        qldbqyinfoPO.setKkpje(qldbqyinfoParam.getKkpje());
        qldbqyinfoPO.setYx(1);
        qldbqyinfoPO.setYszje(qldbqyinfoParam.getYszje());
        qldbqyinfoPO.setWszje(qldbqyinfoParam.getWszje());
        qldbqyinfoPO.setQyzt(qldbqyinfoParam.getQyzt());
        qldbqyinfoPO.setTname(qldbqyinfoParam.getTname());
        qldbqyinfoPO.setTjsj(new Date());
        Boolean i=userMapper.updateQyinfo(qldbqyinfoPO);
        return i;
    }

    @Override
    public boolean deleteContact(UserParam userParam) {
        log.debug("删除用户");
        UserPO userPO = new UserPO();
        userPO.setYhID(userParam.getYhID());
        userPO.setYx(userParam.getYx());
        Boolean a= userMapper.delete(userPO);
        return a;
    }

    @Override
    public List<QldbqyinfoVO> selectContact1(String qymc, String tgszt, Integer pageNum, Integer pageSize) {
        try {
            // 当前账号非admin账号
            String zt = null; // 载体
            if (StringUtils.isNotBlank(tgszt) && !"1".equals(tgszt)) {
                ZtParam ztParam = new ZtParam();
                ztParam.setTgszt(tgszt);
                List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
                if (CollectionUtils.isNotEmpty(ztvos)) {
                    zt = ztvos.get(0).getNr();
                }
            }

            PageHelper.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
            return userMapper.selectEnterpriseList(qymc, zt);
        } catch (Exception e) {
            log.error("查询用户列表异常: {}", e.toString());
            return null;
        }
    }

    @Override
    public boolean switchGate(String khbh, Integer tNumber) {
        log.debug("租户开关闸");
        List<TidParam> tidParamList = userMapper.selectTid(khbh);
        if (tNumber==0){
            for (TidParam tidParam : tidParamList){
                String tid = Integer.toHexString(tidParam.getTid());
                //拉闸操作
                byte[] crcHexString = Crc16Utils.getData(tid,
                        AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_1,
                        AmmeterMessageConstants.AMMETER_PUBLISH_NULL,
                        AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_2,
                        AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_3,
                        AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_3);
                log.debug("CRC效验码（十六进制）: {}", crcHexString);
                // 将CRC校验码转换为十六进制字符串并转换为大写
                String finalMessageHex = Crc16Utils.byteTo16String(crcHexString).toUpperCase();
                log.info("最终消息（十六进制）: {}", finalMessageHex);
                try {
                    byte[] payload = HexUtils.HexStringToByte(finalMessageHex);
                    log.debug("最终消息（十六进制）: {}", payload);
                    // 发送MQTT消息
                    mqttProducer.send(tidParam.getPtopic(), payload);
                    Thread.sleep(2000);
                } catch (Exception e) {
                    // 捕获并抛出异常
                    throw new RuntimeException(e);
                }
                Integer a=ammeterMapper.selectAmmeterStatus(tidParam.getDbbh());
                if (a==0){
                    return true;
                }else {
                    return false;
                }
            }
        }
        return false;
    }

}
